<?php

namespace App\V3\V3_2_7\Controllers;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\ApplicationFormModel;
use App\V3\V3_2_7\Services\ApplicationFormService;
use App\V3\V3_2_7\Services\ApplicationGoodsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use OSS\OssClient;

class ApplicationFormController extends BaseController
{
    /**
     *添加申请表
     * Author: zlf
     * Created at 2024/6/3 9:27
     * @param Request $request
     * @return void
     */
    public function addApplicationForm(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'approver' => 'required',
            'application_time' => 'required',
            'order_type' => [//单据类型：1-采购申请表，2-领用申请表
                'required',
                Rule::in([1, 2])
            ],
            'goods_list' => 'required|json'
        ], [
                'approver.required' => '审批人，不能为空！',
                'application_time.required' => '申请时间，不能为空！',
                'goods_list.required' => '请选择商品！',
                'goods_list.json' => '请求的商品为JSON数据！',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        if (!empty($data['goods_list'])) {
            $data['goods_list'] = json_decode($data['goods_list'], true);
            foreach ($data['goods_list'] as $gVal) {
                $res = self::validGOOdsData($gVal);
                if (!empty($res['code']))
                    return response()->json($res);
            }
        }
        $data['time'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        if (!empty($data['application_time']))
            $data['application_time'] = strtotime($data['application_time']);
        else
            $data['application_time'] = $data['time'];
        if (!empty($request->file('proof_img'))) {
            $imgArr = [];
            $ossClient = new OssClient(
                config('app.aliyun_oss_key'),
                config('app.aliyun_oss_secret'),
                config('app.aliyun_oss_endpoint')
            );
            foreach ($request->file('proof_img') as $v) {
                if ($v->isValid()) {
                    $res = handlePicFormat($v, 'p', '图片格式，不正确！');
                    if (!empty($res)) return response()->json($res);
                    $imgPath = $v->store(date('Y') . '/' . date('m') . '/' . date('d'));
                    $imgRes = addOssUploadImg($data['main_id'], $ossClient, $v, $imgPath);
                    if ($imgRes['code'] == 1) return response()->json($imgRes);
                    $imgArr[] = '/uploads/' . $imgPath;
                } else {
                    return response()->json(['code' => 1, 'msg' => '上传凭证异常！', 'data' => '']);
                }
            }
            $data['proof_img'] = implode(',', $imgArr);
        }
        $qz = $data['order_type'] == 1 ? 'P' : 'R';
        $data['order_no'] = CommonService::getOrderNo(new ApplicationFormModel(), 'order_no', $qz);
        $this->operateLog('申请表', $data, $data['time']);
        return response()->json(ApplicationFormService::addApplicationForm($data));

    }

    /**
     *申请表列表
     * Author: zlf
     * Created at 2024/6/3 16:47
     * @param Request $request
     * @return void
     */
    public function getApplicationList(Request $request)
    {

        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
                'pageSize.required' => '参数`页面大小`缺失',
                'currentPage.required' => '参数`当前页`缺失',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        return $this->success(ApplicationFormService::getApplicationList($data));
    }

    /**
     *审批列表
     * Author: zlf
     * Created at 2024/6/4 17:31
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkApplicationList(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
                'pageSize.required' => '参数`页面大小`缺失',
                'currentPage.required' => '参数`当前页`缺失',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        return $this->success(ApplicationFormService::checkApplicationList($data));
    }

    /**
     *申请表详情
     * Author: zlf
     * Created at 2024/6/4 10:35
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function applicationFormInfo(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//申请单表id
        ], [
                'id.required' => '申请单表`主键`缺失',
                'id.integer' => '申请单表有误',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        return response()->json(ApplicationFormService::applicationFormInfo($data));
    }

    /**
     *删除申请单
     * Author: zlf
     * Created at 2024/6/4 10:35
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delApplicationForm(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//申请单表id
        ], [
                'id.required' => '申请单表`主键`缺失',
                'id.integer' => '申请单表有误',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['time'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $this->operateLog('删除申请表', $data, $data['time']);
        return response()->json(ApplicationFormService::delApplicationForm($data));
    }

    /**
     *审批申请单
     * Author: zlf
     * Created at 2024/6/4 10:35
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkApplicationForm(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//申请单表id
            'approval_status' => ['required',
                Rule::in([1, 2, 3])//审批状态：0待审批、1已同意、2已拒绝、3已完成
            ],//申请单表id
        ], [
                'id.required' => '申请单表`主键`缺失',
                'id.integer' => '申请单表有误',
                'approval_status.required' => '审批状态,不能为空！',
                'approval_status.in' => '审批状态有误',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['time'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $this->operateLog('审批申请表', $data, $data['time']);
        return response()->json(ApplicationFormService::checkApplicationForm($data));
    }

    /**
     *撤销申请表
     * Author: zlf
     * Created at 2024/6/4 10:35
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function repealApplicationForm(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//申请单表id
            'repeal_status' => ['required',
                Rule::in([1])//撤销状态：0-未撤销 1-已撤销
            ],//申请单表id
        ], [
                'id.required' => '申请单表`主键`缺失',
                'id.integer' => '申请单表有误',
                'repeal_status.required' => '撤销状态,不能为空！',
                'repeal_status.in' => '撤销状态有误',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['time'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $this->operateLog('撤销申请表', $data, $data['time']);
        return response()->json(ApplicationFormService::repealApplicationForm($data));
    }

    /**
     *确认收货
     * Author: zlf
     * Created at 2024/6/4 17:13
     * @param Request $request
     * @return void
     */
    public function ApplicationFormConfirmReceipt(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//申请单表id
            'approval_status' => ['required',
                Rule::in([3])//审批状态：3已完成
            ],//申请单表id
        ], [
                'id.required' => '申请单表`主键`缺失',
                'id.integer' => '申请单表有误',
                'approval_status.required' => '确认收货状态,不能为空！',
                'approval_status.in' => '确认收货状态有误',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['time'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $this->operateLog('申请表-确认收货', $data, $data['time']);
        return response()->json(ApplicationFormService::ApplicationFormConfirmReceipt($data));
    }

    /**
     *上传交付凭证图片
     * Author: zlf
     * Created at 2024/6/4 17:13
     * @param Request $request
     * @return void
     */
    public function uploadDeliveryProofImg(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//申请单表id
        ], [
                'id.required' => '申请单表`主键`缺失',
                'id.integer' => '申请单表有误',

            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['time'] = time();
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $this->operateLog('上传交付凭证图片', $data, $data['time']);
        return response()->json(ApplicationFormService::uploadDeliveryProofImg($data));
    }

    /**
     *申请单商品入库详情
     * Author: zlf
     * Created at 2024/6/6 9:47
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function inApplicationGoodsInfo(Request $request)
    {

        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//申请单表id
        ], [
                'id.required' => '申请单表`主键`缺失',
                'id.integer' => '申请单表有误',

            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        return response()->json(ApplicationGoodsService::inApplicationGoodsInfo($data));
    }

    /**
     *申请单商品出库详情
     * Author: zlf
     * Created at 2024/6/6 9:47
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function outApplicationGoodsInfo(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//申请单表id
        ], [
                'id.required' => '申请单表`主键`缺失',
                'id.integer' => '申请单表有误',

            ]
        );
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        return response()->json(ApplicationGoodsService::outApplicationGoodsInfo($data));
    }

    //验证商品数据
    private static function validGOOdsData($goodsData)
    {
        $validator = Validator::make($goodsData, [
            'fir_class_id' => 'required|integer',
            'sec_class_id' => 'required|integer',
            'goods_name' => 'required',
        ], [
                'fir_class_id.required' => '商品一级分类，不能为空！',
                'fir_class_id.integer' => '商品一级分类，必须为整数！',
                'sec_class_id.required' => '商品二级分类，不能为空！',
                'sec_class_id.integer' => '商品二级分类，必须为整数！',
                'goods_name.required' => '商品名称，不能为空！',
            ]
        );
        if ($info = $validator->errors()->first()) {
            return [
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ];
        }
    }

}
